package com.io.example.demoparent.task;



import java.time.Instant;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/***
 * 延迟任务执行方法汇总
 */
public class DelayTaskExample {
    //存放定时任务
    private static Map<String, Long> taskMap = new HashMap<>( );

    private static Boolean aBoolean = Boolean.TRUE;

    public static void main(String[] args) {
        System.out.println("线程启动时间 = " + LocalDateTime.now( ));
        // 添加定时任务
        taskMap.put("task-1", Instant.now( ).plusSeconds(3).toEpochMilli( )); // 延迟 3s
        taskMap.put("task-2", Instant.now( ).plusSeconds(9).toEpochMilli( )); // 延迟 9s
        // 调用无限循环实现延迟任务
        loopTask( );


    }

    /**
     * 无限循环实现延迟任务
     */
    public static void loopTask() {
        Long itemLong = 0L;
        while (aBoolean) {
            Iterator<Map.Entry<String, Long>> entryIterator = taskMap.entrySet( ).iterator( );
            while (entryIterator.hasNext( )) {
                Map.Entry<String, Long> entry = entryIterator.next( );
                itemLong = entry.getValue( );
                //有任务需要执行
                if (Instant.now( ).toEpochMilli( ) >= itemLong) {
                    System.out.println("执行任务：" + entry.getKey( ) +
                            " ，执行时间：" + LocalDateTime.now( ));
                    // 删除任务
                    taskMap.remove(entry.getKey( ));

                }
            }
        }
    }

}
